<?php
include_once ROOT_PATH . 'models/QQGroupModel.class.php';
class Qqgroup extends Action implements IAction {
	/**
	 * <h2>日志对象</h2>
	 *
	 * @var Logger
	 */
	private $_logger;
	/*
	 * 初始化对象
	 */
	public function __construct() {
		parent::__construct ();
		Logger::configure ( ROOT_PATH . 'config/log_config.xml' );
		$this->_logger = Logger::getLogger ( __CLASS__ );
	}
	
	/**
	 * <h2>默认动作</h2>
	 *
	 * @see Action::indexAction()
	 */
	public function indexAction() {
		$vr = new SmartyViewHelper ();
		$request = new Request ();
		$sm = SessionManager::getSingleton ();
		
		$vr->render ( 'file:qqgroup/qqgroup_index.htm' );
	}
	
	/**
	 * <h2>发布QQ群</h2>
	 */
	public function publishAction() {
		$auth = new Auth ();
		if (! $auth->isAuthed ()) {
			$this->_redirect ( '/user/login' );
		}
		$vr = new SmartyViewHelper ();
		$vr->prependTemplateDir ( ROOT_PATH . 'templates/bootstrap' );
		$request = new Request ();
		$sessMgr = SessionManager::getSingleton ();
		$errors = new CMAP ();
		$form = new CMAP ();
		
		if ($request->isPost ()) {
			try {
				// htmLawed Option
				$option = array ();
				// TODO 检验参数
				
				// QQ群号码
				$number = new CSTRING ( $request->getPost ( 'number' ) );
				if (! $number->matches ( '/^[1-9][0-9]*$/' ) || $number->length () < QQGROUP_MIN_LEN || $number->length () > QQGROUP_MAX_LEN) {
					$errors->number = sprintf ( 'QQ群号码长度在%d到%d之间的数字', QQGROUP_MIN_LEN, QQGROUP_MAX_LEN );
					$this->_logger->error ( sprintf ( 'QQ group number [%s] is invalid. Length:%d.', $number->getValue (), $number->length () ) );
				}
				
				// 群名字
				$name = new CSTRING ( $request->getPost ( 'name' ) );
				$name = $name->sanitize ();
				if ($name->length () > QQGROUPNAME_MAX_LEN) {
					$errors->name = sprintf ( '群名字长度不能超过%d', QQGROUPNAME_MAX_LEN );
					$this->_logger->error ( sprintf ( 'QQ group name [%s](%d) is invalid.', $name->getValue (), $name->length () ) );
				}
				
				// 群主名字
				$master = new CSTRING ( $request->getPost ( 'master' ) );
				$master = $master->sanitize ();
				if ($master->length () < QQNICK_MIN_LEN || $master->length () > QQNICK_MAX_LEN) {
					$errors->master = sprintf ( '群主名长度在%d到%d之间', QQNICK_MIN_LEN, QQNICK_MAX_LEN );
					$this->_logger->error ( sprintf ( 'QQ group master\'s nickname [%s](%d) is invalid.', $master->getValue (), $master->length () ) );
				}
				
				// 群主QQ号码
				$masterqq = new CSTRING ( $request->getPost ( 'masterqq' ) );
				if (! $masterqq->matches ( '/^[1-9][0-9]*$/' ) || $masterqq->length () < QQ_MIN_LEN || $masterqq->length () > QQ_MAX_LEN) {
					$errors->masterqq = sprintf ( 'QQ号码长度在%d到%d之间的数字', QQ_MIN_LEN, QQ_MAX_LEN );
					$this->_logger->error ( sprintf ( 'QQ group master\'s QQ Number [%s] is invalid.', $masterqq->getValue () ) );
				}
				
				$category = new CINT ( $request->getPost ( 'category' ) );
				$province = new CINT ( $request->getPost ( 'province' ) );
				$city = new CINT ( $request->getPost ( 'city' ) );
				$district = new CINT ( $request->getPost ( 'district' ) );
				
				// 验证码
				$verifypwd = new CSTRING ( $request->getPost ( 'verifypwd' ) );
				$verifypwd = $verifypwd->sanitize ();
				// TODO 验证码的处理
				
				// 处理介绍
				$intro = new CSTRING ( htmLawed ( $request->getPost ( 'intro' ), $option, null ) );
				
				// 处理图片
				$formseed = new CSTRING ( $request->getPost ( FORM_HASH ) );
				$form->put ( FORM_HASH, $formseed );
				$popImg = json_encode ( $sessMgr->getAttribute ( 'a_' . $formseed->getValue () ) );
				
				if ($errors->size () > 0) {
					throw new ExceptionEx ( 'Invalid POST data.' );
				}
				
				// 填充一个QQGroup实例
				$qg = new CMAP ();
				$qg->number = strval ( $number->getValue () );
				$qg->name = $name->getValue ();
				$qg->master = $master->getValue ();
				$qg->user_id = 1;
				$qg->master_qq = strval ( $masterqq->getValue () );
				$qg->qgcat_id = $category->getValue ();
				$qg->prv_id = $province->getValue ();
				$qg->city_id = $city->getValue ();
				$qg->dist_id = $district->getValue ();
				$qg->verifypwd = $verifypwd->getValue ();
				$qg->intro = $intro->getValue ();
				$qg->image = $popImg;
				$qg->ts_created = time ();
				
				// 获取QQ群操作模型
				$qgm = new QQGroupModel ();
				// 保存
				$status = $qgm->save ( $qg, $newId );
				
				// 检查操作是否成功
				if (STATUS_FAILED == $status) {
					$this->_logger->error ( 'Save QQGroup entity failed. at ' . __LINE__ . ' in ' . __CLASS__ );
					$form->put ( FORM_HASH, $formseed );
				} else {
					// TODO
					$sessMgr->delAttribute ( 'a_' . $formseed->getValue () );
					// forward to success page
					exit ( 'success' . $newId );
				}
			} catch ( ExceptionEx $e ) {
				$this->_logger->error ( $e->getMessage () );
			}
		} // handle post
		
		include_once ROOT_PATH . 'models/QGCategoryModel.class.php';
		$cm = new QGCategoryModel ();
		$catLst = $cm->getAll ();
		include_once ROOT_PATH . 'models/ProvinceModel.class.php';
		$pm = new ProvinceModel ();
		$prvLst = $pm->getAll ();
		if (! $form->containsKey ( FORM_HASH )) {
			$form->put ( FORM_HASH, uniqid () );
			$thumb_img = '';
		} else {
			// 读取thumbnail
			$attachModel = new AttachmentModel ();
			$aList = $sessMgr->getAttribute ( 'a_' . $form->get ( FORM_HASH ) );
			$attach = $attachModel->getDetail ( $aList [0] );
			if ($attach->isEmpty ()) {
				$thumb_img = '';
			} else {
				$uniqname = $attach->get ( 'uniqname' );
				$filename = substr ( $uniqname, 0, strrpos ( $uniqname, '.' ) );
				$fileext = substr ( $uniqname, strrpos ( $uniqname, '.' ) );
				$content = file_get_contents ( UPLOAD_PATH . $filename . THUMB_SUFFIX . $fileext );
				if (! empty ( $content )) {
					$thumb_img = 'data:' . $attach->get ( 'mime' ) . ';base64,' . base64_encode ( $content );
				} else {
					$thumb_img = '';
				}
			}
		}
		// 输出模板
		$vr->assign ( 'qgcats', $catLst );
		$vr->assign ( 'prvs', $prvLst );
		$vr->assign ( 'form', $form );
		$vr->assign ( 'error', $errors );
		$vr->assign ( 'img', $thumb_img );
		$vr->assign ( 'pageTitle', '发布QQ群' );
		$vr->assign ( 'siteTitle', 'QQ群黄页' );
		
		$vr->render ( 'file:qqgroup/publish.htm' );
	}
	
	/**
	 * <h2>QQ群列表</h2>
	 */
	public function listAction() {
		$vr = new SmartyViewHelper ();
		$request = new Request ();
		// 从请求URI中提取参数，并过滤
		$page = new CINT ( $request->getGet ( 'page' ) ); // 分页
		$catId = new CINT ( $request->getGet ( 'cat' ) ); // 分类
		$prvId = new CINT ( $request->getGet ( 'prv' ) ); // 省（自治区，直辖市）
		$cityId = new CINT ( $request->getGet ( 'city' ) ); // 城市
		$distId = new CINT ( $request->getGet ( 'dist' ) ); // 县（区）
		$order = new CINT ( $request->getGet ( 'order' ) ); //
		                                                    
		// 初始化模型查询参数
		$pageNo = $page->getValue ();
		$pageNo == 0 && ++ $pageNo;
		//@formatter:off
   		// 请求列表的条件
		$condition = array();
    	$catId->getValue()   !=  0 && $condition['qgcat_id']  = $catId->getValue ();
		$prvId->getValue ()  !=  0 && $condition['prv_id']  = $prvId->getValue ();
		$cityId->getValue () !=  0 && $condition['city_id'] = $cityId->getValue ();
		$distId->getValue () !=  0 && $condition['dist_id'] = $distId->getValue ();
		// @formatter:on
		$qgm = new QQGroupModel ();
		$cols = array (
				'id',
				'number' 
		);
		if ($order->getValue () != QQGroupModel::ORDER_BY_TS_ASC && $order->getValue () != QQGroupModel::ORDER_BY_TS_DESC) {
			$order->setValue ( QQGroupModel::ORDER_BY_TS_ASC ); // set default
		}
		$qg_main_list = $qgm->getList ( $condition, $cols, $page->getValue (), 20, $order->getValue () ); // 根据条件获取主显列表
		
		$vr->assign ( 'qg_main_list', $qg_main_list );
		
		$vr->render ( 'file:qqgroup/qqgroup_list.htm' );
	}
	
	/**
	 * <h2>我自己创建的群列表</h2>
	 */
	public function myAction() {
		$vr = new SmartyViewHelper ();
		// TODO
		
		$vr->render ( 'file:qqgroup/qqgroup_list.htm' );
	}
	
	/**
	 * 删除QQ群
	 */
	public function deleteAction() {
		echo "删除动作";
		// TODO add code
	}
	
	/**
	 * 更新QQ群
	 */
	public function updateAction() {
		echo "更新动作";
	}
	
	/**
	 * 推荐QQ群
	 */
	public function recommendAction() {
		echo "推荐动作";
	}
	
	/**
	 * 置顶QQ群
	 */
	public function stickAction() {
		echo "置顶";
	}
	
	/**
	 * <h2>处理QQ群详情请求</h2>
	 * <p>从URI中获取GET参数<strong>id</strong>作为要请求的QQ群的id</p>
	 *
	 * @return void
	 */
	public function detailAction() {
		$vr = new SmartyViewHelper ();
		$request = new Request ();
		$id = intval ( $request->getGet ( 'id' ) );
		
		if ($id == 0) {
			exit ( '请求的QQ群不存在' );
		} else {
			$qgm = new QQGroupModel ();
			$qqgroup = $qgm->getDetailById ( $id );
			if ($qqgroup == null) {
				// 没有指定的QQ群，给出错误信息
				exit ( 'not found' );
			} else {
				// 模板赋值，并显示
				$qgm->incHits ( $id );
				$vr->assign ( 'qqgroup', $qqgroup );
				$vr->render ( 'file:qqgroup/qqgroup_detail.htm' );
			}
		}
	}
	
	/*
	 * (non-PHPdoc) @see IAction::addListener()
	 */
	public function addListener(ActionListener $listener) {
		// TODO Auto-generated method stub
	}
	
	/*
	 * (non-PHPdoc) @see IAction::removeListener()
	 */
	public function removeListener(ActionListener $listener) {
		// TODO Auto-generated method stub
	}
	
	/*
	 * (non-PHPdoc) @see IAction::removeAllListener()
	 */
	public function removeAllListener() {
		// TODO Auto-generated method stub
	}
}
